/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.miblounge.gradecalculator.plugin.loader;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import net.miblounge.gradecalculator.plugin.exceptions.PluginException;

public final class PluginLoader {
	private PluginLoader()
	{
	}
	
	public static String getResourceContents(final URLClassLoader loader, final String resource) {
		final InputStream stream = loader.getResourceAsStream(resource);
		final StringBuffer contents = new StringBuffer();
		BufferedReader reader = null;
		 
		try {
			reader = new BufferedReader(new InputStreamReader(stream));
			String text = null;

			while ((text = reader.readLine()) != null) {
				contents.append(text).append(System.getProperty("line.separator"));
			}
		} catch (final Exception e) {
			throw new PluginException("Cannot read resource: " + resource, e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			//CHECKSTYLE:OFF
			} catch (final IOException e) {
			//CHECKSTYLE:ON
			}
		}

		return contents.toString().trim();
	}

	public static Object getPluginByResource(final File file, final String resource)  
	{
		try { 
			final URL pluginURL = file.toURI().toURL();
			final URLClassLoader loader = new URLClassLoader(new URL[] {pluginURL});
			final String className = getResourceContents(loader, resource);
			
			return loader.loadClass(className).newInstance();
		} catch (final MalformedURLException e) {
			throw new PluginException("Error loarding filename: " + file.getAbsolutePath(), e);
		} catch (final ClassNotFoundException e) {
			throw new PluginException("Error loarding plugin " + file.getAbsolutePath(), e);
		} catch (final InstantiationException e) {
			throw new PluginException("Error loarding plugin " + file.getAbsolutePath(), e);
		} catch (final IllegalAccessException e) {
			throw new PluginException("Error loarding plugin " + file.getAbsolutePath(), e);
		}
	}

	public static Object getPluginByResource(final String filename, final String resource)
	{
		final File file = new File(filename);
		return getPluginByResource(file, resource);
	}

}
